package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.util.Result;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ncu.wechat.model.CouponRecord;
import cn.ncu.wechat.service.CouponRecordService;
import cn.ncu.wechat.dao.CouponRecordMapper;
import cn.ncu.wechat.model.dto.CouponRecordDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 
* @description 针对表【coupon_record(优惠券领取记录表)】的数据库操作Service实现
* @createDate 2025-01-07 16:08:19
*/
@Service
public class CouponRecordServiceImpl extends ServiceImpl<CouponRecordMapper, CouponRecord>
    implements CouponRecordService{

    @Override
    public Result distributeCouponRecord(Long id, Integer page, Integer pageSize, Integer status) {
        try {
            if (status != null && status != 1 && status != 2 && status != 3) {
                return Result.error(400, "status只能是1或2或3");
            }
            
            Page<CouponRecord> pageParam = new Page<>(page, pageSize);
            IPage<CouponRecordDTO> pageResult = baseMapper.selectCouponRecordPage(pageParam, id, status);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",pageResult.getRecords());
            jsonObject.put("total",pageResult.getTotal());
            jsonObject.put("size",pageResult.getSize());
            jsonObject.put("current",pageResult.getCurrent());
            jsonObject.put("pages",pageResult.getPages());
            return Result.success(jsonObject);
        } catch (Exception e) {
            return Result.error(500, "发放记录查询失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result sendCouponByArray(Long id, Map<String, Object> request) {
        try {
            if (id == null) {
                return Result.error(400, "优惠券ID不能为空");
            }

            @SuppressWarnings("unchecked")
            List<Integer> memberIdIntegers = (List<Integer>) request.get("memberIds");
            if (memberIdIntegers == null || memberIdIntegers.isEmpty()) {
                return Result.error(400, "会员ID列表不能为空");
            }

            // 将 List<Integer> 转换为 List<Long>
            List<Long> memberIds = memberIdIntegers.stream()
                    .map(Integer::longValue)
                    .toList();

            Integer quantity = null;
            try {
                quantity = Integer.valueOf(String.valueOf(request.get("quantity")));
            } catch (NumberFormatException e) {
                return Result.error(400, "发放数量格式错误");
            }
            if (quantity == null || quantity <= 0) {
                return Result.error(400, "发放数量必须大于0");
            }

            String remark = String.valueOf(request.get("remark"));
            if (remark == null || "null".equals(remark) || remark.trim().isEmpty()) {
                return Result.error(400, "发放备注不能为空");
            }

            List<CouponRecord> recordList = new ArrayList<>();
            Date now = new Date();

            for (Long memberId : memberIds) {
                // 每个会员发放指定数量的优惠券
                for (int i = 0; i < quantity; i++) {
                    CouponRecord record = new CouponRecord();
                    record.setCouponId(id);
                    record.setUserId(memberId);
                    record.setStatus(1);  // 假设1表示已发放未使用
                    record.setGetTime(now);
                    recordList.add(record);
                }
            }

            // 使用 saveBatch 方法批量插入
            boolean success = this.saveBatch(recordList, 100);  // 每100条数据一批

            if (success) {
                return Result.success();
            } else {
                return Result.error(500, "发放失败");
            }

        } catch (Exception e) {
            return Result.error(500, "系统错误：" + e.getMessage());
        }
    }
}




